#include "mainwindow.h"
#include "ui_mainwindow.h"


#include "tcpthread.h"
#include "crc32verifier.h"
#include "tcpDepthWorker.h"
#include "deviceinfo.h"
#include "timeutils.h"
#include "rgbcapture.h"
#include "singleton.h"
#include "rgbvideowidget.h"
//#include "deepvideowidget.h"
#include "aboutdialog.h"
#include "depthdataprocessor.h"
#include "depthClouddataprocessor.h"
#include "tcpIrWorker.h"
#include "depthIrdataprocessor.h"
#include "ftpclient.h"

#include <yaml-cpp/yaml.h>  
#include <QMessageBox>
#include <qtimer.h>
#include <QDateTime>
#include <QtEndian>
#include <QFileDialog>
#include <QProgressDialog>
#include <boost/make_shared.hpp>
#include <QtConcurrent>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    qDebug() << "MainWindow" << QThread::currentThreadId();
    
    m_ftpClient = new FTPClient(this);


    //qRegisterMetaType<QSharedPointer<QImage>>("QSharedPointer<QImage>&");

    connect(ui->DeviceInfoAction, &QAction::triggered, this, &MainWindow::showDeviceInfo);
    connect(ui->OpenPCDAction, &QAction::triggered, this, &MainWindow::openPCDFile);
    connect(ui->RgbViewAction, &QAction::triggered, this, &MainWindow::openRgbViewInfo);
    connect(ui->DeepViewAction, &QAction::triggered, this, &MainWindow::openDeepViewInfo);
    connect(ui->aboutAction, &QAction::triggered, this, &MainWindow::openAboutActionInfo);
    deviceInfo = new DeviceInfo(this);
    connect(deviceInfo, &DeviceInfo::sendRtspIpAddress, this, &MainWindow::onSetRtspIpAddress);
    connect(this, &MainWindow::sendRestartCommand, deviceInfo, &DeviceInfo::onRectReStartCommand);

    rgbViewWidget = new RgbVideoWidget();
    aboutDialog = new AboutDialog();
    // 初始化点云指针
    pointCloud = pcl::make_shared<pcl::PointCloud<pcl::PointXYZ>>();

    rgbCapture = RgbCaptureInstance;
    // 设置超时时间（示例）
    rgbCapture->setConnectTimeout(5000);    // 连接超时5秒
    rgbCapture->setReadTimeout(3000);       // 读取帧超时3秒
    rgbCapture->setOverallTimeout(30000);   // 整体操作超时30秒
    connect(rgbCapture, &RgbCapture::error, this, &MainWindow::handleError);
    connect(rgbCapture, &RgbCapture::clearFrame, ui->videoWidget, &VideoWidget::clearFrame);
    connect(rgbCapture, &RgbCapture::frameReady, ui->videoWidget, &VideoWidget::setFrame);

    connect(rgbCapture, &RgbCapture::stopped, this, &MainWindow::onDecoderStopped);
    tcpDepthWorker = TcpDepthWorkerInstance;
    connect(this, &MainWindow::startPointCloudSignal, deviceInfo, &DeviceInfo::startPointCloudSlot);

    tcpIrWorker = TcpIrWorkerInstance;

    m_processingThread = new QThread();
    m_depthDataProcessor = DepthDataProcessorInstance;
    // 移动处理器到工作线程
    m_depthDataProcessor->moveToThread(m_processingThread);
    m_processingThread->start();

    depthCloudDataProcessor = DepthCloudDataProcessorInstance;
    processCloudThread = new QThread();
    depthCloudDataProcessor->moveToThread(processCloudThread);
    processCloudThread->start();
    connect(this, &MainWindow::sendInitGeneral, depthCloudDataProcessor, &DepthCloudDataProcessor::onRecvInitGeneral);

    depthIrDataProcessor = DepthIrDataProcessorInstance;
    processIrThread = new QThread();
    depthIrDataProcessor->moveToThread(processIrThread);
    processIrThread->start();
    // 假设在主窗口中

    connect(m_depthDataProcessor, &DepthDataProcessor::depthImageReady, this, [this](const QImage& image, const QVector<quint16>& depthData, int width, int height) {
        ui->depthVideo->setFrame(image);          // 更新显示
        ui->depthVideo->setDepthData(depthData, width, height); // 关联深度数据
        }); 

    connect(depthIrDataProcessor, &DepthIrDataProcessor::irImageReady,
        this, [this](const QImage& image, const QVector<quint16>& irData, int width, int height) {
            ui->irVideo->setFrame(image);
            ui->irVideo->setIrData(irData, width, height);
        });
    connect(depthCloudDataProcessor, &DepthCloudDataProcessor::pointCloudReady, ui->openGLWidget, &MyOpenGLWidget::updatePointCloud);
    // 一个信号两个槽连接
    connect(tcpDepthWorker, &TcpDepthWorker::newDataReceived, m_depthDataProcessor, &DepthDataProcessor::processDepthFrame, Qt::QueuedConnection);
    connect(tcpDepthWorker, &TcpDepthWorker::newCloudDataReceived, depthCloudDataProcessor, &DepthCloudDataProcessor::processDepthFrame, Qt::QueuedConnection);
    connect(tcpDepthWorker, &TcpDepthWorker::sendDepthConnectStatus, this, &MainWindow::showDepthConnectStatus, Qt::QueuedConnection);
    connect(tcpIrWorker, &TcpIrWorker::newIrDataReceived, depthIrDataProcessor, &DepthIrDataProcessor::processDepthFrame, Qt::QueuedConnection);

    ui->tabWidget->setCurrentIndex(0);

    // 读取all_node.yaml的值显示到UI上
    readAllNodeYamlConfig();
    initChannelInfo();
}


void MainWindow::onDecoderStopped()
{
    ui->startButton->setEnabled(true);
    ui->stopButton->setEnabled(false);
    //ui->videoLabel->setText("视频已停止");
}

void MainWindow::handleError(const QString& error)
{
    QMessageBox::critical(this, "错误", error);
    ui->startButton->setEnabled(true);
    ui->stopButton->setEnabled(false);
}

MainWindow::~MainWindow()
{
    if (rgbCapture) {
        rgbCapture->stop();
    }
    if (m_processingThread != nullptr && m_processingThread->isRunning())
    {
        m_processingThread->requestInterruption();
        m_processingThread->quit();
        m_processingThread->wait();
        delete m_processingThread;
        m_processingThread = nullptr;
    }
    if (processCloudThread != nullptr && processCloudThread->isRunning())
    {
        processCloudThread->requestInterruption();
        processCloudThread->quit();
        processCloudThread->wait();
        delete processCloudThread;
        processCloudThread = nullptr;
    }
    if (processIrThread != nullptr && processIrThread->isRunning())
    {
        processIrThread->requestInterruption();
        processIrThread->quit();
        processIrThread->wait();
        delete processIrThread;
        processIrThread = nullptr;
    }
    delete ui;
    
}
void MainWindow::onTcpConnected()
{
    qDebug() << "已连接TCP";
    QMessageBox::information(nullptr, "提示", "已连接");
    //emit tcpConnected();

}
void MainWindow::onTcpDisconnected()
{
    qDebug() << "已断开TCP";
    QMessageBox::information(this, "提示", "断开TCP连接");
}


void MainWindow::showDeviceInfo()
{
    deviceInfo->show();

}

void MainWindow::openRgbViewInfo()
{
    rgbViewWidget->show();
}

void MainWindow::openDeepViewInfo()
{
    //deepViewWidget->show();
}

void MainWindow::openPCDFile()
{
    // 打开文件对话框
    QString fileName = QFileDialog::getOpenFileName(this,
        "打开PCD文件",
        QCoreApplication::applicationDirPath(),
        "PCD文件 (*.pcd)");

    qDebug() << "fileName" << fileName;

    if (fileName.isEmpty())
        return;
    // 检查文件是否存在
    QFile file(fileName);
    if (!file.exists()) {
        QMessageBox::critical(this, "错误", "文件不存在: " + fileName);
        return;
    }
    // 检查文件是否可读
    if (!file.open(QIODevice::ReadOnly)) {
        QMessageBox::critical(this, "错误", "无法打开文件: " + fileName);
        return;
    }
    file.close();
    // 打印点云指针状态
    qDebug() << "pointCloud before loading:" << (pointCloud ? "valid" : "null");
    // 清空点云数据
    pointCloud->clear();
    // 读取PCD文件
    int ret = pcl::io::loadPCDFile<pcl::PointXYZ>(fileName.toStdString(), *pointCloud);
    if (ret == -1) {
        QMessageBox::critical(this, "错误", "无法加载PCD文件: " + fileName);
        return;
    }
    // 打印加载后的点云信息
    qDebug() << "Loaded point cloud with" << pointCloud->size() << "points";
    // 检查点云数据是否有效
    if (pointCloud->empty()) {
        QMessageBox::warning(this, "警告", "加载的点云为空");
        return;
    }
    // 更新OpenGL显示
    try {
        ui->openGLWidget->updatePointCloud(pointCloud);
    }
    catch (const std::exception& e) {
        QMessageBox::critical(this, "错误", "更新点云显示失败: " + QString::fromStdString(e.what()));
    }
}

void MainWindow::openAboutActionInfo()
{
    aboutDialog->show();
}





void MainWindow::on_startButton_clicked()
{
    QString url = ui->rtspUrlLineEdit->text().trimmed();
    if (url.isEmpty()) {
        QMessageBox::warning(this, "警告", "请输入有效的RTSP URL");
        return;
    }

    ui->startButton->setEnabled(false);
    ui->stopButton->setEnabled(true);

    QMetaObject::invokeMethod(rgbCapture, [this, url]() {
        rgbCapture->start(url);
        }, Qt::QueuedConnection);

    // 更新按钮状态
    ui->startButton->setEnabled(false);
    ui->stopButton->setEnabled(true);
}


void MainWindow::on_stopButton_clicked()
{
    ui->startButton->setEnabled(true);
    ui->stopButton->setEnabled(false);

    QMetaObject::invokeMethod(rgbCapture, [this]() {
        rgbCapture->stop();
        }, Qt::QueuedConnection);
}


void MainWindow::on_startPointCloud_clicked()
{
    emit startPointCloudSignal();
}

void MainWindow::onSetRtspIpAddress(const QString& ip)
{
    ui->rtspUrlLineEdit->setText(ip);
}

bool MainWindow::checkCloudRange()
{
    // 前三个参数
    double yawValue = ui->yawEdit->text().toDouble();
    if (yawValue < -3.14 || yawValue > 3.14)
    {
        QMessageBox::warning(this,
            tr("范围警告"),
            tr("yaw 值需在 -3.14 到 3.14 之间，请重新输入！"),
            QMessageBox::Ok);
        return false;
    }
    double rollValue = ui->rollEdit->text().toDouble();
    if (rollValue < -3.14 || rollValue > 3.14)
    {
        QMessageBox::warning(this,
            tr("范围警告"),
            tr("roll 值需在 -3.14 到 3.14 之间，请重新输入！"),
            QMessageBox::Ok);
        return false;
    }
    double pitchValue = ui->pitchEdit->text().toDouble();
    if (pitchValue < -3.14 || pitchValue > 3.14)
    {
        QMessageBox::warning(this,
            tr("范围警告"),
            tr("pitch 值需在 -3.14 到 3.14 之间，请重新输入！"),
            QMessageBox::Ok);
        return false;
    }
    //min_ max_
    double minXValue = ui->minXEdit->text().toDouble();
    if (minXValue < 0 || minXValue > 10)
    {
        QMessageBox::warning(this,
            tr("范围警告"),
            tr("minx 值需在 0 到 10 之间，请重新输入！"),
            QMessageBox::Ok);
        return false;
    }
    double maxXValue = ui->maxXEdit->text().toDouble();
    if (maxXValue < 0 || maxXValue > 10)
    {
        QMessageBox::warning(this,
            tr("范围警告"),
            tr("maxX 值需在 0 到 10 之间，请重新输入！"),
            QMessageBox::Ok);
        return false;
    }
    // Y
    double minYValue = ui->minYEdit->text().toDouble();
    if (minYValue < -5 || minYValue > 5)
    {
        QMessageBox::warning(this,
            tr("范围警告"),
            tr("minY 值需在 -5 到 5 之间，请重新输入！"),
            QMessageBox::Ok);
        return false;
    }
    double maxYValue = ui->maxYEdit->text().toDouble();
    if (maxYValue < -5 || maxYValue > 5)
    {
        QMessageBox::warning(this,
            tr("范围警告"),
            tr("maxY 值需在 -5 到 5 之间，请重新输入！"),
            QMessageBox::Ok);
        return false;
    }
    // Z
    double minZValue = ui->minZEdit->text().toDouble();
    if (minZValue < -2 || minZValue > 2)
    {
        QMessageBox::warning(this,
            tr("范围警告"),
            tr("minZ 值需在 -2 到 2 之间，请重新输入！"),
            QMessageBox::Ok);
        return false;
    }
    double maxZValue = ui->maxZEdit->text().toDouble();
    if (maxZValue < -5 || maxZValue > 5)
    {
        QMessageBox::warning(this,
            tr("范围警告"),
            tr("maxZ 值需在 -2 到 2 之间，请重新输入！"),
            QMessageBox::Ok);
        return false;
    }
    // IR
    int IRStartRowValue = ui->IRStartRowEdit->text().toInt();
    if (IRStartRowValue < 350 || IRStartRowValue > 850)
    {
        QMessageBox::warning(this,
            tr("范围警告"),
            tr("IR起始行 值需在 350 到 850 之间，请重新输入！"),
            QMessageBox::Ok);
        return false;
    }
    int IRStartArrValue = ui->IRStartArrEdit->text().toInt();
    if (IRStartArrValue < 0 || IRStartArrValue > 1280)
    {
        QMessageBox::warning(this,
            tr("范围警告"),
            tr("IR起始列 值需在 0 到 1280 之间，请重新输入！"),
            QMessageBox::Ok);
        return false;
    }

    int IREndRowValue = ui->IREndRowEdit->text().toInt();
    if (IREndRowValue < 350 || IREndRowValue > 850)
    {
        QMessageBox::warning(this,
            tr("范围警告"),
            tr("IR终止行 值需在 0 到 1280 之间，请重新输入！"),
            QMessageBox::Ok);
        return false;
    }
    int IREndArrValue = ui->IREndArrEdit->text().toInt();
    if (IREndArrValue < 0 || IREndArrValue > 1280)
    {
        QMessageBox::warning(this,
            tr("范围警告"),
            tr("IR终止列 值需在 0 到 1280 之间，请重新输入！"),
            QMessageBox::Ok);
        return false;
    }
    // cloud
    int CloudStartRowValue = ui->CloudStartRowEdit->text().toInt();
    if (CloudStartRowValue < 350 || CloudStartRowValue > 850)
    {
        QMessageBox::warning(this,
            tr("范围警告"),
            tr("点云起始行 值需在 350 到 850 之间，请重新输入！"),
            QMessageBox::Ok);
        return false;
    }
    int CloudStartArrValue = ui->CloudStartArrEdit->text().toInt();
    if (CloudStartArrValue < 0 || CloudStartArrValue > 1280)
    {
        QMessageBox::warning(this,
            tr("范围警告"),
            tr("点云起始列 值需在 0 到 1280 之间，请重新输入！"),
            QMessageBox::Ok);
        return false;
    }
    // 终止
    int CloudEndRowValue = ui->CloudEndRowEdit->text().toInt();
    if (CloudEndRowValue < 350 || CloudEndRowValue > 850)
    {
        QMessageBox::warning(this,
            tr("范围警告"),
            tr("点云终止行 值需在 350 到 850 之间，请重新输入！"),
            QMessageBox::Ok);
        return false;
    }
    int CloudEndArrValue = ui->CloudEndArrEdit->text().toInt();
    if (CloudEndArrValue < 0 || CloudEndArrValue >1280)
    {
        QMessageBox::warning(this,
            tr("范围警告"),
            tr("点云终止列 值需在 0 到 1280 之间，请重新输入！"),
            QMessageBox::Ok);
        return false;
    }
    // 点云密度
    double CloudDensityValue = ui->CloudDensityEdit->text().toDouble();
    if (CloudDensityValue < 0.0005 || CloudDensityValue > 0.2)
    {
        QMessageBox::warning(this,
            tr("范围警告"),
            tr("点云密度 值需在 0.0005 到 0.2 之间，请重新输入！"),
            QMessageBox::Ok);
        return false;
    }
    return true;
}
void MainWindow::on_saveConfigureBtn_clicked()
{
    // 先确认范围
    
    bool isRangeValid = checkCloudRange();
    if (!isRangeValid)
    {
        return;
    }
    QMessageBox msgBox;
    msgBox.setWindowTitle("确认操作");
    msgBox.setText("以上配置将全部下发到雷达系统，是否确认操作？");
    msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
    msgBox.setDefaultButton(QMessageBox::No);
    // 获取用户点击按钮
    int ret = msgBox.exec();
    if (ret == QMessageBox::Yes)
    {
        QString exeDir = QCoreApplication::applicationDirPath();
        qDebug() << "可执行文件所在目录:" << exeDir;
        // 构建同目录下的文件路径
        QString yamlPath = exeDir + "/all_node.yaml";
        qDebug() << "配置文件路径:" << yamlPath;
        std::string yamlPatchStd = yamlPath.toStdString();
        if (!QFile::exists(yamlPath))
        {
            qDebug() << "错误，文件找不到;" << yamlPath;
            return;
        }
        try 
        {
            YAML::Node config = YAML::LoadFile(yamlPath.toStdString());
            // 保存 /point_detect 节点参数
            if (config["/point_detect"] && config["/point_detect"]["ros__parameters"]) {
                YAML::Node params = config["/point_detect"]["ros__parameters"];

                // 保存角度参数
                params["yaw"] = ui->yawEdit->text().toDouble();
                params["pitch"] = ui->pitchEdit->text().toDouble();
                params["roll"] = ui->rollEdit->text().toDouble();

                // 保存坐标范围参数
                params["min_x"] = ui->minXEdit->text().toDouble();
                params["max_x"] = ui->maxXEdit->text().toDouble();
                params["min_y"] = ui->minYEdit->text().toDouble();
                params["max_y"] = ui->maxYEdit->text().toDouble();
                params["min_z"] = ui->minZEdit->text().toDouble();
                params["max_z"] = ui->maxZEdit->text().toDouble();

                // 保存警告级别
                int warningLevelIndex = ui->CloudWarnLevelComboBox->currentIndex();
                params["warning_level"] = warningLevelIndex + 1; // 索引0对应值1，依此类推

            }
            else {
                qWarning() << "未找到/point_detect节点，将创建新节点";
                // 创建新节点（可选）
                config["/point_detect"]["ros__parameters"]["yaw"] = ui->yawEdit->text().toDouble();
                // ... 其他参数类似添加
            }


            // ------------------ 保存/th_itof节点参数 ------------------
            if (config["/th_itof"] && config["/th_itof"]["ros__parameters"]) {
                YAML::Node params = config["/th_itof"]["ros__parameters"];

                // 保存IR区域参数
                params["amp_start_row"] = ui->IRStartRowEdit->text().toInt();
                params["amp_start_col"] = ui->IRStartArrEdit->text().toInt();
                params["amp_end_row"] = ui->IREndRowEdit->text().toInt();
                params["amp_end_col"] = ui->IREndArrEdit->text().toInt();

                // 保存点云区域参数
                params["dp_start_row"] = ui->CloudStartRowEdit->text().toInt();
                params["dp_start_col"] = ui->CloudStartArrEdit->text().toInt();
                params["dp_end_row"] = ui->CloudEndRowEdit->text().toInt();
                params["dp_end_col"] = ui->CloudEndArrEdit->text().toInt();

                // 保存点云密度
                params["downsample_resolution"] = ui->CloudDensityEdit->text().toDouble();

                // 保存滤波级别
                int filterLevelIndex = ui->CloudFilterLevelComboBox->currentIndex();
                params["filter_level"] = filterLevelIndex + 1; // 索引0对应值1，依此类推
            }
            else {
                qWarning() << "未找到/th_itof节点，将创建新节点";
                // 创建新节点（可选）
            }


            // ------------------ 保存/ros_api节点参数 ------------------
            if (config["/ros_api"] && config["/ros_api"]["ros__parameters"]) {
                YAML::Node params = config["/ros_api"]["ros__parameters"];

                // 保存设备名称
                params["device_name"] = ui->deviceNameEdit->text().toStdString();
            }
            else {
                qWarning() << "未找到/ros_api节点，将创建新节点";
                // 创建新节点（可选）
            }
            QtConcurrent::run([this, yamlPath, config]() {
                // 将更新后的配置写回文件
                std::ofstream fout(yamlPath.toStdString());
                bool success = false;
                QString errorMsg;
                if (fout.is_open()) {
                    fout << config;
                    fout.close();
                    success = true;
                }
                else {
                    errorMsg = "无法打开文件进行写入";
                }
                // 在主线程处理结果
                QMetaObject::invokeMethod(this, [this, success, errorMsg, yamlPath]() {
                    if (success) {
                        qDebug() << "配置文件已成功更新:" << yamlPath;
                        uploadAllNodeYaml();
                        //QMessageBox::information(this, "保存成功", "配置已成功保存到文件");
                    }
                    else {
                        qCritical() << "保存失败:" << errorMsg;
                        QMessageBox::critical(this, "保存失败", "写入配置文件时出错: " + errorMsg);
                    }
                    });


                });

        }catch (const YAML::Exception& e) {
            qCritical() << "YAML处理错误:" << QString::fromStdString(e.what());
            QMessageBox::critical(this, "保存失败", "处理配置文件时出错: " + QString::fromStdString(e.what()));
        }
        catch (const std::exception& e) {
            qCritical() << "保存配置时发生错误:" << QString::fromStdString(e.what());
            QMessageBox::critical(this, "保存失败", "发生未知错误: " + QString::fromStdString(e.what()));
        }
    }
    else {
        qDebug() << "用户选择：不保存并继续";
        return;
    }

}

void MainWindow::uploadAllNodeYaml()
{
    QString ftpUrl = deviceInfo->getFtpUrl();     // 替换为实际FTP服务器地址
    QString username = deviceInfo->getFtpUsername();                  // 替换为实际用户名
    QString password = deviceInfo->getFtpPassword();               // 替换为实际密码
    QString remoteDir = "/uploads";               // 替换为实际远程目录
    if (ftpUrl.isEmpty() || username.isEmpty() || password.isEmpty()) {
        QMessageBox::warning(this, "配置缺失", "请在设备信息中设置FTP服务器配置");
        return;
    }
    QString exeDir = QCoreApplication::applicationDirPath();
    QString localFile = exeDir + "/all_node.yaml";
    QString remoteFile = remoteDir + "/all_node.yaml";

    // 显示上传进度对话框
    QProgressDialog progressDialog("正在上传配置文件...", "取消", 0, 100, this);
    progressDialog.setWindowModality(Qt::WindowModal);
    progressDialog.setMinimumDuration(0);
    progressDialog.show();

    // 连接进度信号
    connect(m_ftpClient, &FTPClient::uploadProgress, &progressDialog, [&](const QString& fileName, int progress) {
        progressDialog.setValue(progress);
        progressDialog.setLabelText(QString("正在上传 %1: %2%").arg(fileName).arg(progress));
        });

    // 连接完成信号
    QFuture<bool> future = m_ftpClient->uploadFileAsync(ftpUrl, username, password, localFile, remoteFile);

    // 管理上传任务
    manageUploadTask(future);
}
#if 1
void MainWindow::manageUploadTask(QFuture<bool> future)
{
    QFutureWatcher<bool>* watcher = new QFutureWatcher<bool>(this);
    watcher->setFuture(future);

    connect(watcher, &QFutureWatcher<bool>::finished, [this, watcher]() {
        bool success = watcher->result();
        //ui->upgradeBtn->setEnabled(true);

        if (success) {
            // 文件上传成功
            QMessageBox::information(this, "成功", "文件下发成功,下位机将会重启,此操作大约耗时20秒");
            //ui->statusLabel->setText("上传完成: " + fileName);
            emit sendRestartCommand();
            // 需要初始化genera
            emit sendInitGeneral();
        }
        else {
            QMessageBox::critical(this, "失败", "文件上传失败，没有权限");
            //ui->statusLabel->setText("上传失败: " + fileName);
        }

        watcher->deleteLater();
        });


}
void MainWindow::initChannelInfo()
{
    
}

#endif


void MainWindow::readAllNodeYamlConfig()
{
    QString exeDir = QCoreApplication::applicationDirPath();
    QString yamlPath = exeDir + "/all_node.yaml";
    // 读取all_node.yaml的值给下面UI赋值,使用libyaml库
    try {
        YAML::Node config = YAML::LoadFile(yamlPath.toStdString());
        if (config["/point_detect"] && config["/point_detect"]["ros__parameters"])
        {
            YAML::Node params = config["/point_detect"]["ros__parameters"];
            // 读取角度参数
            if (params["yaw"]) ui->yawEdit->setText(QString::number(params["yaw"].as<double>()));
            if (params["pitch"]) ui->pitchEdit->setText(QString::number(params["pitch"].as<double>()));
            if (params["roll"]) ui->rollEdit->setText(QString::number(params["roll"].as<double>()));

            // 读取坐标范围参数
            if (params["min_x"]) ui->minXEdit->setText(QString::number(params["min_x"].as<double>()));
            if (params["max_x"]) ui->maxXEdit->setText(QString::number(params["max_x"].as<double>()));
            if (params["min_y"]) ui->minYEdit->setText(QString::number(params["min_y"].as<double>()));
            if (params["max_y"]) ui->maxYEdit->setText(QString::number(params["max_y"].as<double>()));
            if (params["min_z"]) ui->minZEdit->setText(QString::number(params["min_z"].as<double>()));
            if (params["max_z"]) ui->maxZEdit->setText(QString::number(params["max_z"].as<double>()));

            if (params["warning_level"]) {
                int warningLevel = params["warning_level"].as<int>();
                switch (warningLevel)
                {
                case 1:
                    ui->CloudWarnLevelComboBox->setCurrentIndex(0);
                    break;
                case 2:
                    ui->CloudWarnLevelComboBox->setCurrentIndex(1);
                    break;
                case 3:
                    ui->CloudWarnLevelComboBox->setCurrentIndex(2);
                    break;
                default:
                    qWarning() << "未知的warning_level值:" << warningLevel;
                    ui->CloudWarnLevelComboBox->setCurrentIndex(0); // 默认设为低
                    break;
                }
                    
            }


        }
        else {
            qWarning() << "未找到/point_detect节点";
        }
        if (config["/th_itof"] && config["/th_itof"]["ros__parameters"])
        {
            YAML::Node params = config["/th_itof"]["ros__parameters"];

            // 读取IR区域参数
            if (params["amp_start_row"]) ui->IRStartRowEdit->setText(QString::number(params["amp_start_row"].as<int>()));
            if (params["amp_start_col"]) ui->IRStartArrEdit->setText(QString::number(params["amp_start_col"].as<int>()));
            if (params["amp_end_row"]) ui->IREndRowEdit->setText(QString::number(params["amp_end_row"].as<int>()));
            if (params["amp_end_col"]) ui->IREndArrEdit->setText(QString::number(params["amp_end_col"].as<int>()));

            // 读取点云区域参数
            if (params["dp_start_col"]) ui->CloudStartArrEdit->setText(QString::number(params["dp_start_col"].as<int>()));
            if (params["dp_end_col"]) ui->CloudEndArrEdit->setText(QString::number(params["dp_end_col"].as<int>()));

            // 点云密度
            if (params["downsample_resolution"]) ui->CloudDensityEdit->setText(QString::number(params["downsample_resolution"].as<double>()));
            if (params["dp_start_row"]) {
                int startRow = params["dp_start_row"].as<int>();
                ui->CloudStartRowEdit->setText(QString::number(startRow));
                // 计算并设置CloudEndArrEdit的值为dp_end_row - dp_start_row
                if (params["dp_end_row"]) {
                    int endRow = params["dp_end_row"].as<int>();
                    ui->CloudEndRowEdit->setText(QString::number(endRow));
                    int rowCount = endRow - startRow;
                    // 有效线数
                    ui->lineCount->setText(QString::number(rowCount));
                }
            }  

            if (params["filter_level"]) {
                int warningLevel = params["filter_level"].as<int>();
                switch (warningLevel)
                {
                case 1:
                    ui->CloudFilterLevelComboBox->setCurrentIndex(0);
                    break;
                case 2:
                    ui->CloudFilterLevelComboBox->setCurrentIndex(1);
                    break;
                case 3:
                    ui->CloudFilterLevelComboBox->setCurrentIndex(2);
                    break;
                default:
                    qWarning() << "未知的warning_level值:" << warningLevel;
                    ui->CloudFilterLevelComboBox->setCurrentIndex(0); // 默认设为低
                    break;
                }

            }

        }
        else {
            qWarning() << "未找到/th_itof节点";
        }

        if (config["/ros_api"] && config["/ros_api"]["ros__parameters"])
        {
            YAML::Node params = config["/ros_api"]["ros__parameters"];
            // 读取设备名称
            if (params["device_name"])
                ui->deviceNameEdit->setText(QString::fromStdString(params["device_name"].as<std::string>()));
        }
        else {
            qWarning() << "未找到/ros_api节点";
        }

    }
    catch (const YAML::BadFile& e) {
        qCritical() << "无法加载配置文件:" << QString::fromStdString(e.what());
    }
    catch (const YAML::Exception& e) {
        qCritical() << "解析配置文件出错:" << QString::fromStdString(e.what());
    }
    catch (const std::exception& e) {
        qCritical() << "读取配置文件时发生错误:" << QString::fromStdString(e.what());
    }
}




void MainWindow::on_defaultBtn_clicked()
{
    readAllNodeYamlConfig();
}

void MainWindow::showDepthConnectStatus(bool status)
{
    if (status)
    {
        QMessageBox::information(nullptr, "提示", "点云socket已建立连接");
    }
    
}

